package com.sunyur.tailor.channel.service.inner.budget.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.budget.model.BudgetAuditModel;
import com.sunyur.tailor.channel.service.inner.budget.param.*;
import com.sunyur.tailor.channel.service.inner.budget.service.SunyurBudgetService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: tailor_channel
 * @description: //预算类接口
 * @author: pengbing
 * @create: 2021-05-10 15:28
 **/
@Service("SunyurBudgetService")
public class SunyurBudgetServiceImpl implements SunyurBudgetService {
    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurBudgetServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurBudgetServiceImpl.class);
    private static final int MAX_SIZE=20;
    private static final int MAXTS_SIZE=5;
    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 预算单元同步 链接
     */
    @Value("${sunyur.api.batchSyncBudgetUnit}")
    private String batchSyncBudgetUnit;

    /**
     * 预算单元编制结果同步 链接
     */
    @Value("${sunyur.api.batchSyncBudgetAudit}")
    private String batchSyncBudgetAudit;

    /**
     * 预算编制结果批量禁用接口 链接
     */
    @Value("${sunyur.api.batchSyncBudgetStatus}")
    private String batchSyncBudgetStatus;


    /**
     * 预算编制结果查询 链接
     */
    @Value("${sunyur.api.batchQueryBudget}")
    private String batchQueryBudget;

    /**
     * 预算科目同步接口 链接
     */
    @Value("${sunyur.api.batchSyncBudgetSubject}")
    private String batchSyncBudgetSubject;


    /**
     * 成本中心数据同步接口 链接
     */
    @Value("${sunyur.api.batchConfirmBusinessInvoice}")
    private String batchConfirmBusinessInvoice;

    /**
     * 批量新增 修改成本中心数据同步接口 链接
     */
    @Value("${sunyur.api.batchModifyCostCenter}")
    private String batchModifyCostCenter;


    @Override
    public ChannelResult budgetUnitSync(List<BudgetUintParam> budgetUintParam) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.budgetUnitSync, 预算单元数据, 入参条数 {}", JSON.toJSONString(budgetUintParam.size()));
        if (budgetUintParam.isEmpty()) {
            LOGGER_ERROR.error("SunyurBudgetingServiceImpl.budgetUnitSync, 同步预算单元数据为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetServiceImpl budgetUnitSync param is null");
        }
        //根据长度分割
        List<List<BudgetUintParam>> budgetUintParamList=Lists.partition(budgetUintParam,MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BudgetUintParam> budgetUintParams : budgetUintParamList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncBudgetUnit, JSON.toJSONString(budgetUintParams), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("budgetUnitSync loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(budgetUintParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }

    @Override
    public ChannelResult budgetSync(List<BudgetAuditParam> budgetingParam) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.budgetSync, 同步预算档案, 入参 is {}", JSON.toJSONString(budgetingParam));
        if (ObjectUtils.isEmpty(budgetingParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetingServiceImpl budgetSync param is null");
        }
        //根据长度分割
        List<List<BudgetAuditParam>> budgetingParamList=Lists.partition(budgetingParam,MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BudgetAuditParam> budgetAuditParams : budgetingParamList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncBudgetAudit, JSON.toJSONString(budgetAuditParams), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("budgetSync loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(budgetAuditParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }


    @Override
    public ChannelResult batchSyncBudgetStatus(BatchSyncBudgetStatusParam batchSyncBudgetStatusModel) throws Exception {
        LOGGER_INFO.info("SunyurBudgetServiceImpl.batchSyncBudgetStatus, 预算编制结果批量禁用, 入参条数 is {}", JSON.toJSONString(batchSyncBudgetStatusModel.getBudgetOutsideCodes().size()));
        if (ObjectUtils.isEmpty(batchSyncBudgetStatusModel)) {
            LOGGER_ERROR.error("SunyurBudgetServiceImpl.batchSyncBudgetStatus, 预算编制结果批量禁用为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetServiceImpl batchSyncBudgetStatus param is null");
        }
        //根据长度分割
        List<List<String>> budgetOutsideCodesList = Lists.partition(batchSyncBudgetStatusModel.getBudgetOutsideCodes(), MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        BatchSyncBudgetStatusParam batchSyncBudgetStatusParamClient = new BatchSyncBudgetStatusParam();
        for (List<String> strings : budgetOutsideCodesList) {
            batchSyncBudgetStatusParamClient.setBudgetOutsideCodes(strings);
            batchSyncBudgetStatusParamClient.setModifyCode(batchSyncBudgetStatusModel.getModifyCode());
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncBudgetStatus, JSON.toJSONString(batchSyncBudgetStatusParamClient), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("batchSyncBudgetStatus loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchSyncBudgetStatusParamClient), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }


    @Override
    public ChannelResult<List<BudgetAuditModel>> batchQueryBudget(BatchSyncBudgetQueryParam batchSyncBudgetQueryModel) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.batchQueryBudget, 预算编制结果查询, 入参 is {}", JSON.toJSONString(batchSyncBudgetQueryModel));
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.batchQueryBudget, 预算编制结果查询, 入参条数 is {}", JSON.toJSONString(batchSyncBudgetQueryModel.getBudgetOutsideCodes().size()));
        if (ObjectUtils.isEmpty(batchSyncBudgetQueryModel)) {
            LOGGER_ERROR.error("SunyurBudgetingServiceImpl.batchQueryBudget, 预算编制结果查询数据为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurPurchaseApplyServiceImpl getPurchaserApplyItemsHeadByCode param is null");
        }
        //查询结果
        List<BudgetAuditModel> resultList = new ArrayList<>();
        //根据长度分割
        List<List<String>> budgetOutsideCodesList = Lists.partition(batchSyncBudgetQueryModel.getBudgetOutsideCodes(), MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        BatchSyncBudgetQueryParam batchSyncBudgetQueryParamClient = new BatchSyncBudgetQueryParam();
        TypeReference<SunyurResult<List<BudgetAuditModel>>> typeReference = new TypeReference<SunyurResult<List<BudgetAuditModel>>>() {
        };
        for (List<String> strings : budgetOutsideCodesList) {
            batchSyncBudgetQueryParamClient.setBudgetOutsideCodes(strings);
            // 调用主线接口
            SunyurResult<List<BudgetAuditModel>> sunyurResult = sunyurClient.execPost(batchQueryBudget, JSON.toJSONString(batchSyncBudgetQueryParamClient), typeReference);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("batchQueryBudget loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchSyncBudgetQueryParamClient), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(resultList);
    }


    @Override
    public ChannelResult batchSyncBudgetSubject(List<BatchSyncSubjecBudgetParam> reqParamList) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.batchSyncBudgetSubject, 预算科目数据, 入参条数 {}", JSON.toJSONString(reqParamList.size()));
        if (reqParamList.isEmpty()) {
            LOGGER_ERROR.error("SunyurBudgetingServiceImpl.batchSyncBudgetSubject, 同步预算科目数据为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetServiceImpl batchSyncBudgetSubject param is null");
        }
        List<List<BatchSyncSubjecBudgetParam>> batchSyncSubjecBudgetParamList=Lists.partition(reqParamList,MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BatchSyncSubjecBudgetParam> batchSyncSubjecBudgetParams : batchSyncSubjecBudgetParamList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncBudgetSubject, JSON.toJSONString(batchSyncSubjecBudgetParams), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("batchSyncBudgetSubject loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchSyncSubjecBudgetParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }


    @Override
    public ChannelResult batchSyncCostCenter(List<BatchSyncCostCenterParam> reqParamList) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.batchSyncCostCenter, 同步成本中心基础数据, 入参条数 {}", JSON.toJSONString(reqParamList.size()));
        if (reqParamList.isEmpty()) {
            LOGGER_ERROR.error("SunyurBudgetingServiceImpl.batchSyncCostCenter, 同步成本中心基础数据为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetServiceImpl batchSyncCostCenter param is null");
        }
        List<List<BatchSyncCostCenterParam>> batchSyncCostCenterParamList=Lists.partition(reqParamList,MAX_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BatchSyncCostCenterParam> batchSyncCostCenterParams : batchSyncCostCenterParamList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchConfirmBusinessInvoice, JSON.toJSONString(batchSyncCostCenterParams), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("batchSyncCostCenter loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchSyncCostCenterParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }

    @Override
    public ChannelResult batchModifyCostCenter(List<BatchSyncCostCenterParam> reqParamList) throws Exception {
        LOGGER_INFO.info("SunyurBudgetingServiceImpl.batchModifyCostCenter, 同步成本中心基础数据, 入参条数 {}", JSON.toJSONString(reqParamList.size()));
        if (reqParamList.isEmpty()) {
            LOGGER_ERROR.error("SunyurBudgetingServiceImpl.batchModifyCostCenter, 同步成本中心基础数据为空");
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurBudgetServiceImpl batchModifyCostCenter param is null");
        }
        List<List<BatchSyncCostCenterParam>> batchSyncCostCenterParamList=Lists.partition(reqParamList,MAXTS_SIZE);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BatchSyncCostCenterParam> batchSyncCostCenterParams : batchSyncCostCenterParamList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchModifyCostCenter, JSON.toJSONString(batchSyncCostCenterParams), null);
            if (!"success".equals(sunyurResult.getCode())) {
                LOGGER_ERROR.error("batchModifyCostCenter loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchSyncCostCenterParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }
}
